package com.ruoyi.framework.utils;

import net.dreamlu.mica.core.spring.SpringContextUtil;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.util.concurrent.Executor;

/**
 * @author dyun
 */
@Configuration
public class MailUtils {

    private static MailProperties mailProperties;
    private static JavaMailSender javaMailSender;

    public MailUtils(MailProperties mailProperties, JavaMailSender javaMailSender) {
        MailUtils.mailProperties = mailProperties;
        MailUtils.javaMailSender = javaMailSender;
    }

    /**
     * 基于富文本模板发送邮件
     *
     * @param toMailAddress 收件人邮箱
     * @param subject       主题
     * @param content       内容
     * @throws Exception
     */
    public static void send(String[] toMailAddress, String subject, String content) throws Exception {
        MimeMessage message = javaMailSender.createMimeMessage();
        // 第二个参数表示是否开启multipart模式
        MimeMessageHelper messageHelper = new MimeMessageHelper(message);
        messageHelper.setFrom(mailProperties.getUsername());
        messageHelper.setTo(toMailAddress);
        messageHelper.setSubject(subject);
        // 第二个参数表示是否html，设为true
        messageHelper.setText(content, true);

        Executor taskExecutor = SpringContextUtil.getBean("taskExecutor");
        taskExecutor.execute(() -> {
            javaMailSender.send(message);
        });
    }
}
